package org.example.xxl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang.time.DateUtils;
import org.example.config.AlipayConts;
import org.example.config.ZzyUtils;
import org.example.entity.*;
import org.example.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class xxlJobAdviseTransport {
    @Autowired
    ISysLogisticsService iSysLogisticsService;
    @Autowired
    ISysLogisticsXxljobService iSysLogisticsXxljobService;
    @Autowired
    ISysDeiversService iSysDeiversService;
    @Autowired
    ISysCropService iSysCropService;
    @Autowired
    IAdviseTransportService iAdviseTransportService;
    @Autowired
    IPayPlanService iPayPlanService;
    @XxlJob("PullAlipayOrderJob")
    public ReturnT<String> pullAlipayOrderJob(String param) throws Exception {
        System.out.println("正在调度=========");
       //通知
        tongzhi();
        doOrder();
        doOutTimeAnd();
        return ReturnT.SUCCESS;
    }
    public void tongzhi(){
        //查询物流对比表是否存在待运输的货物
        LambdaQueryWrapper<SysLogisticsXxljob> sysLogisticsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysLogisticsLambdaQueryWrapper.eq(SysLogisticsXxljob::getState,4);
        List<SysLogisticsXxljob> list = iSysLogisticsXxljobService.list(sysLogisticsLambdaQueryWrapper);
        //如果存在
        if(CollectionUtil.isNotEmpty(list)){
            for (SysLogisticsXxljob sysLogisticsXxljob : list) {
                //根据物流表关联的司机id去查询司机的手机号 发送消息
                SysDeivers sysDeivers = iSysDeiversService.getById(sysLogisticsXxljob.getDeiverId());
                boolean b = ZzyUtils.sendSms(sysDeivers.getPhone(), "您有一个通知");
                if(b==true){
                    LambdaQueryWrapper<SysCrop> sysCropLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sysCropLambdaQueryWrapper.eq(SysCrop::getCropNumbering,sysLogisticsXxljob.getLogisticsNumber());
                    SysCrop sysCrop = iSysCropService.getOne(sysCropLambdaQueryWrapper);
                    final LambdaQueryWrapper<AdviseTransport> adviseTransportLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    adviseTransportLambdaQueryWrapper.eq(AdviseTransport::getCropId,sysCrop.getId());
                    AdviseTransport adviseTransport = iAdviseTransportService.getOne(adviseTransportLambdaQueryWrapper);
                    adviseTransport.setState(6);
                    iAdviseTransportService.updateById(adviseTransport);
                    sysLogisticsXxljob.setState(6);
                    iSysLogisticsXxljobService.updateById(sysLogisticsXxljob);
                    SysLogistics sysLogistics = BeanUtil.copyProperties(sysLogisticsXxljob, SysLogistics.class);
                    sysLogistics.setState(6);
                    iSysLogisticsService.updateById(sysLogistics);
                }
            }
        }
    }
    //超时关闭
    public void doOutTimeAnd() throws AlipayApiException {
        LambdaQueryWrapper<PayPlan> payPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        payPlanLambdaQueryWrapper.eq(PayPlan::getState,1);
        payPlanLambdaQueryWrapper.le(PayPlan::getCreateTime, DateUtils.addMinutes(new Date(),-2));
        final List<PayPlan> list = iPayPlanService.list(payPlanLambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(list)){
            for (PayPlan payPlan : list) {
                // 初始化SDK
                AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;

                // 构造请求参数以调用接口
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel model = new AlipayTradeQueryModel();

                // 设置订单支付时传入的商户订单号
                model.setOutTradeNo(payPlan.getOutTradeNo());

                // 设置查询选项
                List<String> queryOptions = new ArrayList<String>();
                queryOptions.add("trade_settle_info");
                model.setQueryOptions(queryOptions);

                // 设置支付宝交易号

                request.setBizModel(model);
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                System.out.println(response.getBody());
                String tradeStatus = response.getTradeStatus();
                String subCode = response.getSubCode();
                if(StrUtil.equalsIgnoreCase(tradeStatus,AlipayConts.TRADE_CLOSED)||StrUtil.equalsIgnoreCase(subCode,AlipayConts.TRADE_NOT_EXIST)){
                    System.out.println("====超时关闭或不存在====");
                    payPlan.setState(3);
                    iPayPlanService.updateById(payPlan);
                }
            }
        }
    }
    //处理订单
    public void doOrder() throws AlipayApiException {
        LambdaQueryWrapper<PayPlan> payPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        payPlanLambdaQueryWrapper.eq(PayPlan::getState,1);
        List<PayPlan> list = iPayPlanService.list(payPlanLambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(list)){
            for (PayPlan payPlan : list) {
                // 初始化SDK
                AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
                // 构造请求参数以调用接口
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel model = new AlipayTradeQueryModel();
                // 设置订单支付时传入的商户订单号
                model.setOutTradeNo(payPlan.getOutTradeNo());
                // 设置查询选项
                List<String> queryOptions = new ArrayList<String>();
                queryOptions.add("trade_settle_info");
                model.setQueryOptions(queryOptions);
                // 设置支付宝交易号
                //model.setTradeNo("2014112611001004680 073956707");
                request.setBizModel(model);
                AlipayTradeQueryResponse response = alipayClient.execute(request);
                System.out.println(response.getBody());
                if (response.isSuccess()) {
                    System.out.println("=====支付宝调用成功=====");
                    if(StrUtil.equalsIgnoreCase(response.getTradeStatus(),AlipayConts.TRADE_SUCCESS)){
                        iPayPlanService.doOrder(response.getOutTradeNo(),response.getTradeNo());
                    }
                }
            }
        }
    }



}
